package com.laan.bmagame;

import java.util.ArrayList;
import java.util.Random;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;

public class Nuvols {
	
	private ArrayList<Objecte> nuvols;
	private static final int NUVOLSMAX = 8;
	private static final float BASEWIDTH = 250f;
	private static final int VARWIDTH = 250;
	private static final float BASEHEIGHT = 125f;
	private static final int VARHEIGHT = 150;
	private static final float BASEVX = 0.0015f;
	private static final int VARVX = 40;
	private Random rand;
	Resources resources;
	BitmapFactory.Options options;
	
	public Nuvols(Resources res) {
		if(GV.Instancies.nuvols == null) {
			nuvols = new ArrayList<Objecte>();
			GV.Instancies.nuvols = nuvols;
		}
		else nuvols = GV.Instancies.nuvols;
		rand = new Random();
		options = new BitmapFactory.Options();
		options.inPreferredConfig = Bitmap.Config.ARGB_8888;
		resources = res;
	}
	
	public void actualitza() {
		toca_afegir();
		for(int i=nuvols.size()-1; i>=0; i--) {
			Objecte nuvol = nuvols.get(i);
			nuvol.actualitza();
			if((nuvol.vx > 0 && nuvol.x > GV.Screen.metrics.widthPixels) || (nuvol.vx < 0 && nuvol.x < -nuvol.width)) nuvols.remove(i);
		}
	}
	
	public void draw(Canvas canvas) {
		for(Objecte o: nuvols) o.draw(canvas);
	}
	
	private void toca_afegir() {
		if(nuvols.size() == NUVOLSMAX) return;
		for(int i=nuvols.size(); i<NUVOLSMAX; i++) {
			Bitmap nuvol;
			if(rand.nextInt(2)==0) nuvol = BitmapFactory.decodeResource(resources, R.drawable.cloud1, options);
			else nuvol = BitmapFactory.decodeResource(resources, R.drawable.cloud2, options);
			float x,y,width,height,vx,vy;
			width = (BASEWIDTH+(float)rand.nextInt(VARWIDTH))/1000*GV.Screen.metrics.widthPixels;
			height = (BASEHEIGHT +(float)rand.nextInt(VARHEIGHT))/1000*GV.Screen.metrics.heightPixels;
			y = (float)rand.nextInt(GV.Screen.metrics.heightPixels-(int)height);
			vx = (BASEVX+(float)rand.nextInt(VARVX)/10000)*GV.Screen.metrics.widthPixels;
			vy = 0;
			if(rand.nextInt(2)==0) {
				x = -width;
			}
			else {
				x = GV.Screen.metrics.widthPixels;
				vx = -vx;
			}
			nuvols.add(new Objecte(nuvol,x,y,width,height,vx,vy));
		}
	}
}
